//
//  MainViewController.m
//  PhongThuyHuongNha
//
//  Created by Le Anh Tai on 9/28/13.
//  Copyright (c) 2013 Le Anh Tai. All rights reserved.
//

#import "MainViewController.h"
#import "UIConstants.h"
#import "PhongThuy/SunLunar.h"
#import <QuartzCore/QuartzCore.h>
#import "PhongThuy/NguHanh.h"
#import "Utility.h"
#import "HuongInfoCell.h"
#import "HeaderSectionResultView.h"

#define WIDTH_BIRTHDAY 200

#define HEIGHT_BIRTHDAY 40
#define HEIGHT_GENDER 45

#define toRad(X) (X*M_PI/180.0)
#define toDeg(X) (X*180.0/M_PI)

@interface MainViewController ()

@end

@implementation MainViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    if (self)
    {
        // Custom initialization
    }
    
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	
    self.view.backgroundColor = COLOR_BLACK_PURE;
    NSDate *date = [NSDate date];
    
    //fengShui
    _homeDirection = [[HomeDirection alloc] init];
    
    _fengShuiCore = [[FengShuiCore alloc] init];
    _fengShuiCore.isMale = DEFAULT_GENGER_MALE;
    _fengShuiCore.lunarDate = [_fengShuiCore convertToLunarDate:[NSDate dateWithDay:date.day month:date.month year:date.year - 28]];
    _isAmLich = NO;
    
    //Header
    _headerView.backgroundColor = COLOR_BLACK_PURE;
    
    _titleLabel.backgroundColor = [UIColor clearColor];
    _titleLabel.textColor = COLOR_BLUE_IOS7;
    _titleLabel.text = @"HƯỚNG NHÀ - HƯỚNG BẾP";
    
    //header result view
    _ownerInfoHeaderView = [[HeaderResultView alloc] init];
    _ownerInfoHeaderView.titleLabel.text = @"HƯỚNG TỐT/XẤU CỦA GIA CHỦ";
    
    //Thong tin gia chu
    _ownerInfoView.backgroundColor = [UIColor clearColor];
    _ownerInfoTitleLabel.backgroundColor = [UIColor clearColor];
    _ownerInfoTitleLabel.textColor = COLOR_WHITE;
    
    //Compass
    _compassView.backgroundColor = [UIColor clearColor];
    _compassScrollView.backgroundColor = [UIColor clearColor];
    _batQuaiScrollView.backgroundColor = [UIColor clearColor];
    [_batQuaiScrollView setHidden:YES];
    _directionLabel.textColor = COLOR_WHITE;
    _directionLabel.text = @"";        
    
    //footerView
    _footerView.backgroundColor = COLOR_LIGHT_BLACK;
    _footerLabel.textColor = COLOR_WHITE;    
    _footerLabel.text = @"hocthuatphuongdong.vn © Copyright 2013";
    _footerView.hidden = YES;
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureCopyrighthandler:)];
    [_footerView addGestureRecognizer:tapGesture];
    
    //owner info
    [self initializeOwnerInfoCallout];
    
    _explainationView = [[UIView alloc] init];
    [_compassView addSubview:_explainationView];
    
    //info compass webview
    _infoCompassWebView = [[UIWebView alloc] init];
    _infoCompassWebView.backgroundColor = [UIColor whiteColor];
    _infoCompassWebView.opaque = NO;
    _infoCompassWebView.delegate = self;
    _infoCompassWebView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
//    _infoCompassWebView.delegate = self;
    NSString *filePath=[[NSBundle mainBundle]pathForResource:@"diengiaiCompass" ofType:@"html" inDirectory:nil];
    [_infoCompassWebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];
    
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureHandler:)];
    [_explainationView addGestureRecognizer:panGesture];
    
    UISwipeGestureRecognizer *swipeLeftGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGestureHandler:)];
    swipeLeftGesture.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.view addGestureRecognizer:swipeLeftGesture];
    
    UISwipeGestureRecognizer *swipeDownGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGestureHandler:)];
    swipeDownGesture.direction = UISwipeGestureRecognizerDirectionDown;
    [self.view addGestureRecognizer:swipeDownGesture];
    
    UISwipeGestureRecognizer *swipeUpGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGestureHandler:)];
    swipeUpGesture.direction = UISwipeGestureRecognizerDirectionUp;
    [self.view addGestureRecognizer:swipeUpGesture];
    
    _currentHeading = 0.0;
}

- (void)tapGestureCopyrighthandler:(UITapGestureRecognizer*)tapGesture
{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://hocthuatphuongdong.vn/"]];
}

- (void)swipeGestureHandler:(UISwipeGestureRecognizer*)gesture
{
    if (gesture.direction == UISwipeGestureRecognizerDirectionDown)
    {
        [self birthDayButtonPressed:nil];
    }
    else if (gesture.direction == UISwipeGestureRecognizerDirectionLeft)
    {
        [self infoButtonPressed:nil];
    }
    else if (gesture.direction == UISwipeGestureRecognizerDirectionUp)
    {
        [_ownerInfoCallout close];
    }
}

- (void)initializeOwnerInfoCallout
{
    _ownerInfoCallout = [self newOwnerInfoCalloutView];
    _ownerInfoCallout.delegate = self;
    _ownerInfoCallout.width = 300;
}

- (void)loadDataOwnerInfo
{
    if (_isAmLich)
    {
        _ownerInfoCallout.birthday = _fengShuiCore.lunarDate;
    }
    else
    {
        _ownerInfoCallout.birthday = [_fengShuiCore convertToSunDate: _fengShuiCore.lunarDate];
    }
    
    _ownerInfoCallout.isAmLich = _isAmLich;
    _ownerInfoCallout.isMale = _fengShuiCore.isMale;
}

- (OwnerInfoCalloutView *)newOwnerInfoCalloutView
{
    return nil;
}

- (UIColor *)colorForStatusBackgroundView
{
    return _headerView.backgroundColor;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    _explainationView.frame = RECT(_compassView.width, 0, _compassView.width, _compassView.height);
    
    [self birthDayButtonPressed:_birthdayButton];
    [self updateBirthdayButton];
    
    [self startLocationHeadingEvents];
    //    [self updateHeadingDisplays];
}

- (void)viewWillDisappear:(BOOL)animated
{
    if (_locationManager)
    {
        [_locationManager stopUpdatingHeading];
        [_locationManager stopUpdatingLocation];
    }
    
    [super viewWillDisappear:animated];
}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
}

- (void)switchChanged:(SevenSwitch*)sender
{
    _fengShuiCore.isMale = sender.on;
}

- (void)showResult
{
    //override
    [self removeInfoCompassWebView];
}

- (void)updateOwnerInfoCalloutToFengShuiCore
{
    _fengShuiCore.isMale = _ownerInfoCallout.isMale;
    _isAmLich = _ownerInfoCallout.isAmLich;
    
    if (_isAmLich)
    {
        _fengShuiCore.lunarDate = _ownerInfoCallout.birthday;
    }
    else
    {
        _fengShuiCore.lunarDate = [_fengShuiCore convertToLunarDate:_ownerInfoCallout.birthday];
    }
}

- (void)loadWebViewFile:(NSString *)content
{
    NSString *pathTemplate = [[NSBundle mainBundle] pathForResource:@"Result" ofType:@"html"];
    NSMutableString *mtstrHtmlMasterContent = [NSMutableString stringWithContentsOfFile:pathTemplate encoding:NSUTF8StringEncoding error:nil];
    
    NSString *pathCss = [[NSBundle mainBundle] pathForResource:@"styles" ofType:@"css"];
    
    pathCss = [NSString stringWithFormat:@"%@%@",@"file://",pathCss];
    
    [self htmlReplaceStr:@"~css~" withString:pathCss inString:mtstrHtmlMasterContent];
    [self htmlReplaceStr:@"~content~" withString:content inString:mtstrHtmlMasterContent];
}

- (void)htmlReplaceStr:(NSString*) aStr1 withString:(NSString*) aStr2 inString:(NSMutableString*) aString
{
    NSRange range;
    
    range.location = 0;
    range.length = aString.length;
    [aString replaceOccurrencesOfString:aStr1 withString:aStr2 options:NSLiteralSearch range:range];
    
    //[aString stringByReplacingOccurrencesOfString:aStr1 withString:aStr2];
}

- (void)panGestureHandler:(UIPanGestureRecognizer *)recognizer
{
    CGPoint currentTouchPoint     = [recognizer locationInView:self.compassView];
    CGFloat curX = currentTouchPoint.x;
    
    if (recognizer.state == UIGestureRecognizerStateBegan)
    {
        _preTouchX = curX;
    }
    else if (recognizer.state == UIGestureRecognizerStateChanged)
    {
        CGFloat dx = curX - _preTouchX;
        
        CGFloat newCenterPosition = _explainationView.center.x + dx;
        //        NSLog(@"center:%f, dx:%f",newCenterPosition, _movingView.center.x);
        if (newCenterPosition < [self anchorCenter])
        {
            newCenterPosition = [self anchorCenter];
        }
        else if(newCenterPosition > [self anchorRightCenter])
        {
            newCenterPosition = [self anchorRightCenter];
        }
        
        CGPoint center = CGPointMake(newCenterPosition, _explainationView.center.y);
        
        _explainationView.center = center;
        _preTouchX = curX;
    }
    else if (recognizer.state == UIGestureRecognizerStateEnded || recognizer.state == UIGestureRecognizerStateCancelled)
    {
        CGPoint currentVelocityPoint = [recognizer velocityInView:_explainationView];
        CGFloat currentVelocityX     = currentVelocityPoint.x;
        //swiping right
        if (currentVelocityX > 0)
        {
            //            NSLog(@"End swipe right");
            
            [self animationToX:self.anchorRightCenter velocity:currentVelocityX forView:_explainationView];
        }
        //swiping left
        else
        {
            //            NSLog(@"End swipe left");
            [self animationToX:self.anchorCenter velocity:currentVelocityX forView:_explainationView];
        }
    }
}

- (void)animationToX:(CGFloat)x velocity:(CGFloat)vel forView:(UIView*)view
{
    CGFloat distant = abs(view.center.x - x);
    CGFloat time = [Utility estimateTimeWithDis:distant andVelocity:abs(vel)];
    [UIView animateWithDuration:time animations:^{
        view.center = CGPointMake(x, view.center.y);
    }];
}

- (CGFloat)anchorCenter
{
    return (self.view.bounds.size.width / 2);
}

- (CGFloat)anchorRightCenter
{
    return (self.view.bounds.size.width * 1.5);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //override
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //override
    return nil;
}

- (void)addInfoCompassWebView
{
    if (_infoCompassWebView.superview)
    {
        return;
    }
    
    [_explainationView addSubview:_infoCompassWebView];
    _infoCompassWebView.delegate = self;
    _infoCompassWebView.frame = _explainationView.bounds;
    [_infoCompassWebView.scrollView setContentOffset:CGPointZero animated:YES];
}

- (void)removeInfoCompassWebView
{
    if (_infoCompassWebView.superview == nil)
    {
        return;
    }
    
    [_infoCompassWebView removeFromSuperview];
}

#pragma mark - Delegate owner info close

- (void)OwnerInfoCalloutViewDidClosed:(OwnerInfoCalloutView *)view
{
    [self updateOwnerInfoCalloutToFengShuiCore];
    [self updateBirthdayButton];
}

- (void)updateBirthdayButton
{
    [_birthdayButton setBackgroundColor:(_ownerInfoCallout.isMale ? COLOR_BLUE_IOS7 : COLOR_PINK)];

    NSString *info = [NSString stringWithFormat:@"%@, %@ %@",[_fengShuiCore genderString],[_ownerInfoCallout.birthday stringddmmyyyy],_ownerInfoCallout.isAmLich?@"Âm lịch":@"Dương lịch"];
    [_birthdayButton setTitle:info forState:UIControlStateNormal];
}

#pragma mark - UIWebView delegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *link = [request.URL baseURL];
    
    if (navigationType == UIWebViewNavigationTypeLinkClicked)
    {
        [self closeExplanationView];
        
        return NO;
    }
    
    return YES;
}

- (void)footerResultViewDidPressLink:(FooterResultView *)view
{
    [self closeExplanationView];
}

#pragma mark - button pressed
- (IBAction)birthDayButtonPressed:(id)sender
{
    if (_ownerInfoCallout.superview)
    {
        return;
    }
    
    [self closeExplanationView];
    
    [self loadDataOwnerInfo];
    [_ownerInfoCallout showInView:self.view];
    _ownerInfoCallout.centerX = self.view.width/2;
    _ownerInfoCallout.top = _ownerInfoTitleLabel.bottom + _ownerInfoTitleLabel.superview.top - 6;
    _ownerInfoCallout.height = _ownerInfoCallout.calculatedHeight;
    
//    _ownerInfoCallout.subView.alpha = 0;
//    [UIView transitionWithView:_ownerInfoCallout
//                      duration:1
//                       options:UIViewAnimationOptionTransitionCurlDown
//                    animations:^ {
//                        _ownerInfoCallout.height = _ownerInfoCallout.calculatedHeight;
//                        _ownerInfoCallout.subView.alpha = 1;
//                    }
//                    completion:^(BOOL finished) {
//                        if (finished)
//                        {
//
//                        }
//                    }];
}

- (void)infoButtonPressed:(id)sender
{
    [self showResult];
    
    [self reviewExplanationView];
}

- (IBAction)infoCompassPressed:(id)sender
{
    [self addInfoCompassWebView];
    
    [self reviewExplanationView];
}

- (void)reviewExplanationView
{
    if (_explainationView.left > [self anchorCenter])
    {
        [self animationToX:[self anchorCenter] velocity:0.4 forView:_explainationView];
    }
}

- (void)closeExplanationView
{
    if (_explainationView.centerX != [self anchorRightCenter])
    {
        [self animationToX:self.anchorRightCenter velocity:0.4 forView:_explainationView];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)updateBatQuaiImage:(NSString *)batQuaiImage
{
    [_batQuaiScrollView setHidden:NO];
    
    [_batQuaiImage setImage:[UIImage imageNamed:batQuaiImage]];
    
    [UIView animateWithDuration: 0.3
                          delay: 0.0
                        options: UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveEaseOut | UIViewAnimationOptionAllowUserInteraction
                     animations: ^{
                         CGAffineTransform rotation = CGAffineTransformRotate(CGAffineTransformIdentity, (CGFloat)-toRad(_currentHeading));

                         self.batQuaiScrollView.transform = rotation;
                     }
                     completion: ^(BOOL finished){
                     }
     ];
}

- (void)updateHeadingDisplays
{
    [UIView animateWithDuration: 0.3
                          delay: 0.0
                        options: UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveEaseOut | UIViewAnimationOptionAllowUserInteraction
                     animations: ^{
                         CGAffineTransform rotation = CGAffineTransformRotate(CGAffineTransformIdentity, (CGFloat)-toRad(_currentHeading));
                         
                         self.compassScrollView.transform = rotation;
                         self.batQuaiScrollView.transform = rotation;
                     }
                     completion: ^(BOOL finished){
                     }
     ];
}

- (void)startLocationHeadingEvents
{
    //
    if (_locationManager)
    {
        return;
    }
    
    _locationManager = [[CLLocationManager alloc] init];
    
    _locationManager.delegate = self;
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    _locationManager.headingFilter = 1;
    
    [_locationManager startUpdatingHeading];
}

- (NSString*)getDirectionStringFromDegree:(int)degree
{
    if ( degree >= 360-23 )
    {
        degree = 0;
    }
    else
    {
        degree += 23;
    }
    
    float index = ( degree/45.0 );
    
    return [_TAM_HUONG objectAtIndex:ceilf(index)-1];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
//    CLLocationDirection heading_old = ( (manager.heading.trueHeading > 0) ? manager.heading.trueHeading : manager.heading.magneticHeading );
//    CLLocationDirection heading_new = ( (newHeading.trueHeading > 0) ? newHeading.trueHeading : newHeading.magneticHeading );
//    
//    // Convert degree to radian
//	float oldRad = -heading_old * M_PI / 180.0f;
//	float newRad = -heading_new * M_PI / 180.0f;
//    
//    //
//	CABasicAnimation *theAnimation;
//	theAnimation=[CABasicAnimation animationWithKeyPath:@"transform.rotation"];
//	theAnimation.fromValue = [NSNumber numberWithFloat:oldRad];
//	theAnimation.toValue=[NSNumber numberWithFloat:newRad];
//	theAnimation.duration = 0.5f;
//	
//    [_compassScrollView.layer addAnimation:theAnimation forKey:@"animateCompassRotation"];
//	_compassScrollView.transform = CGAffineTransformMakeRotation(newRad);
//    
//    [_batQuaiScrollView.layer addAnimation:theAnimation forKey:@"animateBatQuaiRotation"];
//	_batQuaiScrollView.transform = CGAffineTransformMakeRotation(newRad);
//    
//    self.directionLabel.text = [NSString stringWithFormat:@"%d° %@", (int)heading_new, [self getDirectionStringFromDegree:heading_new]];
    
    
    
//    if (newHeading.headingAccuracy <= 0)
//    {
//        return;
//    }

//    NSLog(@"[UpdateHeading] trueHeading = %d, magneticHeading = %d", newHeading.trueHeading, newHeading.magneticHeading);
    
    CLLocationDirection heading = ( (newHeading.trueHeading > 0) ? newHeading.trueHeading : newHeading.magneticHeading );
    
    _currentHeading = heading;
    
    self.directionLabel.text = [NSString stringWithFormat:@"%d° %@", (int)_currentHeading, [self getDirectionStringFromDegree:_currentHeading]];
    
    [self updateHeadingDisplays];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    if ([error code] == kCLErrorDenied)
    {
        NSLog(@"Stop updating compass");
        
        // User has denied the application's request to use location services.
        [_locationManager stopUpdatingHeading];
    }
    else if ([error code] == kCLErrorHeadingFailure)
    {
        // Heading could not be determined
    }
}

- (void)viewDidUnload
{
    [self setHeaderView:nil];
    [self setTitleLabel:nil];
    [self setDirectionLabel:nil];
    [self setOwnerInfoTitleLabel:nil];
    
    [self setCompassScrollView:nil];
    [self setFooterView:nil];
    [self setFooterLabel:nil];
    [self setOwnerInfoView:nil];
    [self setCompassView:nil];
    [self setBatQuaiScrollView:nil];
    [self setBatQuaiImage:nil];
    [super viewDidUnload];
}
@end
